package org.hpm.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hpm.bo.HpmUserBO;
import org.hpm.common.util.CookieUtils;
import org.hpm.common.api.vo.HpmResult;
import org.hpm.common.constant.CommonConstant;
import org.hpm.common.constant.enums.Sex;
import org.hpm.common.util.MD5Util;
import org.hpm.entity.HpmUsers;
import org.hpm.mapper.HpmUsersMapper;
import org.hpm.service.IHpmUsersService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @description: 用户表
 * @author: jacklin
 * @date: 2021-11-24
 * @version: V1.0
 */
@Slf4j
@Service
public class HpmUsersServiceImpl extends ServiceImpl<HpmUsersMapper, HpmUsers> implements IHpmUsersService {

    @Override
    public boolean usernameIsExist(String username) {
        int count = this.lambdaQuery().eq(HpmUsers::getUsername, username).count();
        return count > 0 ? true : false;
    }

    @Override
    public HpmResult<?> createUser(HpmUserBO userBO, HttpServletRequest request, HttpServletResponse response) {
        HpmUsers user = new HpmUsers();
        try {

            String username = userBO.getUsername();
            String password = userBO.getPassword();
            String confirmPassword = userBO.getConfirmPassword();
            if (StringUtils.isAnyBlank(username, password, confirmPassword)) {
                return HpmResult.errorMsg("用户名或密码不能为空");
            }
            //校验用户名是否存在
            boolean isExist = usernameIsExist(username);
            if (isExist) {
                return HpmResult.errorMsg("该用户名已存在");
            }
            if (password.length() < 6) {
                return HpmResult.errorMsg("密码长度不能小于6");
            }
            if (!password.equals(confirmPassword)) {
                return HpmResult.errorMsg("两次输入密码不一致");
            }
            user.setUsername(username);
            user.setPassword(MD5Util.MD5Encode(password, "utf-8"));
            //默认用户昵称为user_6位随机字符串
            user.setNickname("user_" + RandomUtil.randomString(6));
            //默认头像
            user.setFace(CommonConstant.USER_FACE);
            //默认生日
            user.setBirthday(null);
            //默认性别为保密
            user.setSex(Sex.SECRET.code);
            user.setCreateTime(new Date());
            baseMapper.insert(user);

            user = setNullProperty(user);
            //将用户信息保存到cookie里面
            CookieUtils.setCookie(request, response, "user", JSONObject.toJSONString(user), true);


        } catch (Exception e) {
            log.error("注册失败", e);
            return HpmResult.errorMsg("注册失败");
        }

        return HpmResult.ok("注册成功", user);
    }

    @Override
    public HpmResult<?> login(HpmUserBO userBO, HttpServletRequest request, HttpServletResponse response) {
        HpmUsers userResult = new HpmUsers();
        try {
            String username = userBO.getUsername();
            String password = userBO.getPassword();
            if (StringUtils.isAnyBlank(username, password)) {
                return HpmResult.errorMsg("用户名或密码不能为空");
            }
            //校验用户名是否存在
            boolean isExist = usernameIsExist(username);
            if (!isExist) {
                return HpmResult.errorMsg("该用户名不存在，请先注册！");
            }
            //实现登录
            userResult = this.lambdaQuery().eq(HpmUsers::getUsername, username).eq(HpmUsers::getPassword, MD5Util.MD5Encode(password, "utf-8")).one();
            if (userResult == null) {
                return HpmResult.errorMsg("用户名密码不正确！");
            }

            userResult = setNullProperty(userResult);
            //将用户信息保存到cookie里面
            CookieUtils.setCookie(request, response, "user", JSONObject.toJSONString(userResult), true);

        } catch (Exception e) {
            log.error("登录失败", e);
            return HpmResult.errorMsg("登录失败");
        }
        return HpmResult.ok("登录成功", userResult);
    }

    @Override
    public HpmResult logout(String userId, HttpServletRequest request, HttpServletResponse response) {
        //清除用户的相关cookie信息
        CookieUtils.deleteCookie(request, response, "user");

        // TODO: 2022/8/31
        // TODO 用户退出登录，需要清空购物车
        // TODO 分布式回话中需要清除用户数据
        return HpmResult.ok();
    }

    private HpmUsers setNullProperty(HpmUsers userResult) {
        userResult.setRealname(null);
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setCreateTime(null);
        userResult.setUpdateTime(null);
        userResult.setBirthday(null);
        return userResult;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println(RandomUtil.randomString(6));
        }
    }
}
